<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/***********************************************************************\
| @package		Auth
| @author		Dennis T. Kaplan
| @copyright	Copyright (c) 2007, PzzAzz LLC
| @license		
| @link			http://www.pzzazz.com
| @since		Version 1.0
| @category		Libraries
\***********************************************************************/

class Auth 
{
	/*****************************************\
	| Auth Constructor
	\*****************************************/
    
    var $caller;
	
	function __construct()
	{
		$this->CI =& get_instance();
        $this->caller = False;
        log_message('debug', "Auth Library Class Initialized");
	}

	/******************Replaced in models/pdb.php ***************************
	* Get alias and password
	*
	* @param varchar $alias
	* @param varchar $pass
	* @return object

	function Login($a, $p)
	{
		$where = array('Alias'=>$a, 'Password'=>$p);
        $this->db->select('uid');
		$this->db->where($where);
		$this->db->from('contact_user');
        $this->db->limit(1);
		$data = $this->db->get();
      return $data; 
	}
	*/
	
	/**
	* Authorization Check
	**/
	public function CheckTaMeR($lock)
	{
        $this->caller = 'CheckTaMeR';
		settype($account, "object");
		$keys = FALSE;
		
		if($this->CheckLogin() !== TRUE) //Checking session here
		{
			$this->cookieLogin();
		}
        $keys = $this->CI->session->userdata('groups');
		$this->CheckAccess($lock,$keys);
	}

	public function CheckLogin()
	{
		if($this->CI->session->userdata('login') === TRUE){
            return TRUE;
		}else{
             $uri = $this->CI->uri->segment(1).'/'.$this->CI->uri->segment(2,'') ;
                set_Cookie('location',$uri,3600);
            if($this->caller === FALSE){
                redirect('/control_panel/login', 'location');
            }else{
                return FALSE;
            }
		}
	}
	
    private function cookieLogin()
    {
        $key = get_cookie('Auth');
        if($key !== FALSE)
        {
            $this->CI->db->select('uid,Alias,groups');
            $this->CI->db->from('contact_user');
            $this->CI->db->where('cookie', $key);
            $this->CI->db->limit(1);
            $query = $this->CI->db->get();
            if($query->num_rows() > 0){
                $row = $query->row_array();
                $row['login'] = TRUE;
                $this->CI->session->regenerate_id();
                $this->CI->session->set_userdata($row);
                $this->CI->msg->setMsg('INFO: Login via cookie. Restricted access.');
            }else{
                log_message('debug', "Login Control 30");
                redirect('/control_panel/login', 'location');
            }
        }else{
            log_message('debug', "Login Control 40");
            redirect('/control_panel/login', 'location');
        }
    }


	/**************************************************\
	| If Post save is checked this will be called to 
	| create a cookie!
	\**************************************************/
    // set_Cookie('name','value','seconds');
	public function addCookie() 
	{
		// Create a unique key
		$uid = $this->CI->session->userdata('uid');
		$key = md5(uniqid(mt_rand(), true));
		$ip = $this->CI->fun->getip();
		$expire = 60*60*24*90;
		set_cookie('Auth', $key, $expire);
		
		$data = array(
			'cookie' => $key,
			'IP' => $ip
			);
		$this->CI->db->where('uid', $uid);
		$this->CI->db->update('contact_user', $data);
	}

	private function CheckAccess($lock,$keys)
	{
        $check = FALSE;
        $lock = explode(',', str_replace(' ', '', $lock));
        $lock[] = 101; # Admin has always access
        if($keys !== FALSE){
            $keys = explode(',', str_replace(' ', '', $keys));
        }else{
            log_message('debug', "Login Control 45");
            $check = FALSE;
            redirect('/control_panel/login/', 'location');
        }
        
        foreach($lock as $k => $v)	{
            if (in_array($v, $keys)) {
                $check = TRUE;
            }
            if ($v == 100){
                if( ! in_array(100, $keys)) {
                    log_message('debug', "Login Control 50");
                    redirect('/control_panel/login/', 'location');
                    $check = FALSE;
                }
                log_message('debug', "Login Control 60");
                $lock[$k] = FALSE;
            }
        }
        if ($check === TRUE){
        	return TRUE;
        }else{
            log_message('debug', "Login Control 70");
        	show_error("You don't have access to this area.");
        }
	}

    public function LogOut()
	{
            $this->CI->session->sess_destroy();
            del_cookie('Auth');
            redirect('/', 'location');
	}

    public function SendPass($alias, $email, $pass)
    {
		 $host = $_SERVER['HTTP_HOST'];
		 
		 $subject= "Your " .$host. " login info.";
		 $message = 
		 "Welcome back to " .$host. "\r\n\r\n"
		 ."You already have an account with us "
		 ."following is your login information:\r\n\r\n"
		 ."Alias: " .$alias. "\r\n"
		 ."Password: " .$pass. "\r\n"
		 ."http://".$host. "\r\n\r\n\r\n"
		 ."If you have received this mail in error, "
		 ."you do not need to take any action. \r\n"
		 ."You will not receive any further emails. \r\n\r\n"
		 ."Thank you for using " .$host. ".\r\n\r\n"
		 ."This is a post-only mailing. "
		 ."Replies to this message are not monitored or answered.";
		 
		 $this->fun->SendEmail($email, $subject , $message);
    }
}


?>
